package com.gt.web.srv.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.RegisteredPayload;
import com.gt.web.api.exception.BusinessException;
import com.gt.web.srv.enums.RespEnum;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author 18304
 */
@Slf4j
public class JwtUtils {

    /**
     * 私钥
     */
    private static final String JWT_PRIVATE_KEY = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855TU.123234@";

    /**
     * token过期时间一周
     */
    private static final int EXPIRATION_ONE_HOUR = 24 * 7;

    private static final String DEFAULT_USER_PAYLOAD = "userData";

    /**
     * 用户信息加密 token
     *
     * @param jwtData
     * @param <T>
     */
    public static <T> String createToken(T jwtData) {
        OptUtil.ifThrow(Optional.empty().equals(jwtData), "加密信息为空,无法执行!");

        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.HOUR, EXPIRATION_ONE_HOUR);
        Map<String, Object> payload = new HashMap<>();
        //签发时间
        payload.put(RegisteredPayload.ISSUED_AT, now);
        //过期时间
        payload.put(RegisteredPayload.EXPIRES_AT, newTime);
        //生效时间
        payload.put(RegisteredPayload.NOT_BEFORE, now);
        //载荷
        payload.put(DEFAULT_USER_PAYLOAD, jwtData);
        return JWTUtil.createToken(payload, JWT_PRIVATE_KEY.getBytes());
    }

    /**
     * jwt 解密
     *
     * @param tokenString
     * @param tClass
     * @param <T>
     */
    public static <T> T checkToken(String tokenString, Class<T> tClass) {
        JWT jwt = JWTUtil.parseToken(tokenString);
        boolean verifyKey = jwt.setKey(JWT_PRIVATE_KEY.getBytes()).verify();
        OptUtil.ifThrow(!verifyKey, RespEnum.RESPONSE_CODE_NO_PERMISSION.getDesc());
        return jwt.getPayloads().getBean(DEFAULT_USER_PAYLOAD, tClass);
    }

    private JwtUtils() {
        throw new IllegalStateException("JwtUtils Utility class");
    }
}
